package com.bl.student.api.filters;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.core.config.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created by yujingyi on 2017/5/10.
 */
@Log4j2
@WebFilter(
        filterName = "crosFilter",
        urlPatterns = "/*",
        initParams = {
        @WebInitParam(name= "allowOrigin", value="*"),
} )
@Order(1)
public class CrosFilter implements Filter {

    private static final String HEADER_ORIGIN = "Origin";
    private static final String HEADER_ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";

    private static final String HEADER_ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
    private static final String HEADER_ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
    private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";

    private static final String ALLOW_HEADERS_VALUE = "Content-Type, api_key, Authorization";
    private static final String ALLOW_METHODS_VALUE = "GET, POST, DELETE, PUT, PATCH, OPTIONS";
    private static final String ALLOW_CREDENTIALS_VALUE = "true";

    private FilterConfig filterConfig;
    private List<String> allowOrigins;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        String allowOrigin = this.filterConfig.getInitParameter("allowOrigin");
        if(!Strings.isNullOrEmpty(allowOrigin)){
            allowOrigins = Splitter.on(',')
                    .omitEmptyStrings()
                    .trimResults()
                    .splitToList(allowOrigin);
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)throws IOException, ServletException {

        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if(allowOrigins != null && allowOrigins.size() > 0){
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            String origin = httpRequest.getHeader(HEADER_ORIGIN);
//            log.info("request origin : " + origin);
            //允许所有域跨域访问
            if(allowOrigins.contains("*")){
                //允许请求带cookie，所以需要精确域名，不能用*
                httpResponse.addHeader(HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, origin);
            }else{
                if(allowOrigins.contains(origin)){
                    httpResponse.addHeader(HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, origin);
                }
            }
        }
        httpResponse.addHeader(HEADER_ACCESS_CONTROL_ALLOW_METHODS, ALLOW_METHODS_VALUE);
        httpResponse.addHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, ALLOW_CREDENTIALS_VALUE);
        httpResponse.addHeader(HEADER_ACCESS_CONTROL_ALLOW_HEADERS, ALLOW_HEADERS_VALUE);

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

}


